package com.port.serial;





import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;



public class MainActivity extends Activity {

	
	static final int COMM_RECV = 102;
	
	boolean m_started;
	
	EventHandler m_eventHandler;
	SerialComm m_comm;
	TextView tvdata;
	int tvCount;
	String m_strRecvBuf;
	int m_fd;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getInstance().m_activity = this;
        setContentView(new MainView(this));     
        tvdata = (TextView) findViewById(R.id.show_1);
        
        tvCount = 0;
        
        m_eventHandler = new EventHandler();
        
        m_comm = new SerialComm(m_eventHandler, 256);
        
        m_fd = m_comm.openPort("/dev/ttyUSB0", 57600, 1, 1);
        
        m_comm.start();
        
        OutputLogWindow("m_fd = " + m_fd);
        
    }

 /*   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }*/
    
    @Override
    public void onDestroy() {
    	if (m_comm != null && m_comm.isAlive()) {
    		m_comm.destroy();	
    	}
    	m_comm.closePort();
    	
    	super.onDestroy();
   
    }
    
    @Override
    public void onResume() {
    	super.onResume();
    	
    	
    }
    @Override
    public void onPause() {
    	super.onPause();
    	if (m_comm != null && m_comm.isAlive()) {
    		m_started = false;
    		m_comm = null;
    	}
   		   		
		//m_comm.closePort();	
        
    }
    
    public void OutputLogWindow(String buf) {
    	/*if (tvCount == 1) {
    		tvCount = 0;*/
    		tvdata.setText(buf);
    	/*} else {
    		String tempStr = new String(tvdata.getText().toString());
    		tempStr += new String(buf);
    		
    		tvdata.setText(tempStr);
    		tvCount++;*/
    	}
    //}
    
    public void updateData() {
    	OutputLogWindow(m_strRecvBuf);
    }
    
    public class EventHandler extends Handler {
    	EventHandler() {}
    	
    	public void handleMessage(Message msg) {
    		
    		if (msg.what == COMM_RECV) {
    			m_strRecvBuf = new String(m_comm.recv());
    			
    			updateData();
    			
    		}
    		
    		return;
    	}
    	
    	
    	
    }
}
